<template>
  <div class="login-container">
    <van-nav-bar
        title="用户登录"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />
    <div class="login-form">
      <img src="@/assets/学校logo.png" alt="学校 Logo" class="school-logo" />
      <h1 class="title">大学报修系统</h1>
      <van-field v-model="username" placeholder="请输入学号或者职工号" left-icon="contact" />
      <van-field v-model="password" type="password" placeholder="请输入密码" left-icon="closed-eye" />
      <div class="verification-container">
        <van-field v-model="verificationCode" placeholder="请输入验证码" />
        <div @click="refreshCode" class="captcha-container">
          <s-identify :identifyCode="identifyCode"></s-identify>
        </div>
      </div>
      <div class="options-container">
        <van-checkbox v-model="rememberUsername">记住用户名</van-checkbox>
        <span class="forgot-password" @click="onForgotPassword">找回密码</span>
      </div>
      <van-button type="primary" block @click="onLogin">登录</van-button>
      <van-button type="default" block @click="onRegister">注册</van-button>
    </div>
    <Alert v-if="showToast" :theme="toastTheme" :message="toastMessage" :duration="3000" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import axios from 'axios';
import SIdentify from '../SIdentify.vue';
import Alert from '../MessageAlert.vue';

const router = useRouter();
const store = useStore();

const username = ref('');
const password = ref('');
const verificationCode = ref('');
const identifyCode = ref('');
const showToast = ref(false);
const toastMessage = ref('');
const toastTheme = ref('info');
const rememberUsername = ref(false);

const onClickLeft = () => {
  router.back(); // 返回上一页
};

const randomNum = (min, max) => {
  return Math.floor(Math.random() * (max - min) + min);
};

const refreshCode = () => {
  identifyCode.value = '';
  makeCode(identifyCode, 4);
};

const makeCode = (codeRef, length) => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < length; i++) {
    codeRef.value += characters[randomNum(0, characters.length)];
  }
};

refreshCode();

const showAlert = (message, theme) => {
  toastMessage.value = message;
  toastTheme.value = theme;
  showToast.value = true;
};

const onLogin = async () => {
  if (!username.value || !password.value || !verificationCode.value) {
    showAlert('请输入用户名、密码和验证码', 'warning');
    return;
  }

  if (verificationCode.value.toLowerCase() !== identifyCode.value.toLowerCase()) {
    showAlert('验证码错误', 'error');
    return;
  }

  try {
    const response = await axios.post('/api/users/login', {
      username: username.value,
      password: password.value,
    });

    if (response.data.success) {
      showAlert('登录成功', 'success');
      store.dispatch('login', response.data.user); // 保存用户信息到Vuex
      router.push('/home');
    } else {
      showAlert('登录失败，请检查用户名和密码', 'error');
    }
  } catch (error) {
    console.error('登录失败:', error);
    showAlert('登录失败，请重试', 'error');
  }
};

const onRegister = () => {
  router.push('/student-register');
};

const onForgotPassword = () => {
  router.push({ name: 'studentForget', path: '/login/student-forget' }); // 修改为跳转到子路由
};
</script>


<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');

.login-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}

.login-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 20px;
  margin-top: 20px;
}

.school-logo {
  width: 250px; /* 调整 Logo 图片的宽度 */
  margin-bottom: 100px; /* 调整间距 */
}

.title {
  font-family: 'Roboto', sans-serif; /* 使用 Google Fonts 提供的字体 */
  font-size: 24px;
  font-weight: 700; /* 加粗标题文字 */
  color: #333;
  margin-bottom: 20px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1); /* 添加文字阴影 */
  letter-spacing: 0.5px; /* 调整字母间距 */
}

.van-field {
  margin-bottom: 10px;
  width: 100%;
}

.verification-container {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 10px;
}

.captcha-container {
  margin-left: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 38px; /* 设置与输入框一致的高度 */
  width: 112px; /* 设置验证码图片的宽度 */
  cursor: pointer;
}

.options-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.forgot-password {
  color: #409eff;
  font-size: 14px;
  cursor: pointer;
}

.van-button {
  margin-top: 10px;
}

.footer {
  background: url('@/assets/footer-bg.jpg') no-repeat center center;
  background-size: cover;
  padding: 20px 0;
  text-align: center;
}

.footer-text {
  color: white;
  margin: 0;
}
</style>
